package sourceagile.server.subversionFileRepository.specification;

import java.io.ByteArrayOutputStream;
import java.util.Collection;
import java.util.Iterator;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.tmatesoft.svn.core.SVNDirEntry;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNNodeKind;
import org.tmatesoft.svn.core.SVNProperties;
import org.tmatesoft.svn.core.io.SVNRepository;

import sourceagile.server.subversionFileRepository.ConvertFileToJson;
import sourceagile.server.subversionFileRepository.GetSubversionClassFile;
import sourceagile.server.subversionFileRepository.SubversionRepositoryConnection;
import sourceagile.server.utilities.FileExtensions;

public class GenerateSpecificationFile {

	public static JSONArray listEntries(String repositoryURL, String username,
			String password) {

		JSONArray entries = new JSONArray();

		SVNRepository repository;
		try {

			repository = SubversionRepositoryConnection.connect(repositoryURL,
					username, password);

			listFilesFromFolder(repository, "", entries);

		} catch (SVNException e) {

			e.printStackTrace();

		}

		return entries;
	}

	private static void listFilesFromFolder(SVNRepository repository,
			String folder, JSONArray entries) throws SVNException {

		Collection subversionEntries = repository.getDir(folder, -1, null,
				(Collection) null);

		Iterator iterator = subversionEntries.iterator();

		while (iterator.hasNext()) {

			SVNDirEntry subversionEntry = (SVNDirEntry) iterator.next();

			if (subversionEntry.getKind() != SVNNodeKind.FILE) {

				listFilesFromFolder(repository,
						getFolderPath(folder, subversionEntry), entries);

			} else {

				JSONObject classDocument = ConvertFileToJson
						.convertFromSubversion(subversionEntry, folder);

				String fileExtension = FileExtensions
						.getFileExtension(subversionEntry.getName());

				if (FileExtensions.EXTENSION_JAVA.equals(fileExtension)
						|| FileExtensions.EXTENSION_FEATURE
								.equals(fileExtension)) {

					ByteArrayOutputStream baos = new ByteArrayOutputStream();

					SVNProperties fileProperties = new SVNProperties();

					repository.getFile(
							folder + "/" + subversionEntry.getName(), -1,
							fileProperties, baos);

					classDocument = GetSubversionClassFile.getJson(
							classDocument, baos.toString(),
							subversionEntry.getName());
				}

				entries.put(classDocument);
			}
		}
	}

	public static String getFolderPath(String path, SVNDirEntry subversionEntry) {

		String folderPath = (path.equals("")) ? subversionEntry.getName()
				: path + "/" + subversionEntry.getName();

		return folderPath;
	}

}
